import request from "../../request/index"
// pages/detail/detail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    detailData: {
      pics: [],
      goods_introduce: "",
      goods_name: "",
      goods_id: "",
      goods_price: ""
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getDetailData(options.goods_id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
   

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //获取商品详情数据
  getDetailData(goods_id) {
    request("GET", "/goods/detail", { goods_id }).then(res => {
      console.log(res)
      let { pics,
        goods_introduce,
        goods_name,
        goods_id,
        goods_price } = res
      let detailData = {
        pics,
        goods_introduce,
        goods_name,
        goods_id,
        goods_price
      }
      this.setData({
        detailData
      })
    })
  },
  //图片预览
  openpreviewImage(e) {
    let curIndex = e.target.dataset.index
    let urls = this.data.detailData.pics.map(item => item.pics_mid)
    wx.previewImage({
      current: urls[curIndex], // 当前显示图片的http链接
      urls // 需要预览的图片http链接列表
    })
  },
  //加入购物车
  addCart() {
    let cart = wx.getStorageSync('cart') || []
    let currentGoods = cart.find(item => {
      return item.goods_id == this.data.detailData.goods_id
    })
    if (currentGoods) {
      //如果存在 数量+1
      currentGoods.num++
    } else {
      //不过不存在添加到cart中
    }
  }
})